# -*- coding: utf-8 -*-
# @author: HRUN

import os
import subprocess
from celery import shared_task

from performance.models import PerformanceTask
from performance.serializers import PerformanceTaskRunSerializer
from performanceengine.params import save_data


@shared_task
def run_task(task_id, env_id):
    # 获取执行任务的数据
    task = PerformanceTask.objects.get(pk=task_id)
    task_data = PerformanceTaskRunSerializer(task).data
    presetting = task_data['presetting']
    scene_list = []
    for scene in task_data['taskScence']:
        steps = scene['taskscencestep_set']
        # 排序
        steps.sort(key=lambda x: x['sort'])

        def process_item(item):
            processed_item = {**item['stepInfo'], **{'children': []}}
            if 'children' in item:
                processed_item['children'] = [process_item(child) for child in item['children']]
            return processed_item

        scene_list.append({'steps': [process_item(item) for item in steps], 'name': scene['name'], 'env': scene['env'][0] if scene['env'] else None, 'weight': scene['weight']})

    data = {'scenes': scene_list, 'presetting': {**presetting},'env': env_id}

    # 将 data 存储到 params.py 文件
    save_data(data)

    return data


def kill_process_using_port(port):
    # 查找占用端口的 PID
    result = subprocess.run(f"netstat -ano | findstr :{port}", shell=True, capture_output=True, text=True)
    lines = result.stdout.strip().split('\n')

    # 如果没有输出，表示端口没有被占用
    if not lines or lines[0] == '':
        print(f"No process found using port {port}.")
        return

    for line in lines:
        parts = line.split()
        if len(parts) >= 5:  # 确保这一行有足够的部分，避免 IndexError
            pid = parts[-1]
            # 终止该进程
            try:
                os.kill(int(pid), 9)  # 使用 SIGKILL 强制终止进程
                print(f"Terminated process with PID {pid} occupying port {port}.")
            except Exception as e:
                print(f"Error terminating process: {e}")
        else:
            print(f"Invalid line format: {line}")